//
//  FinishedOrder.m
//  RRQS
//
//  Created by kuyuZJ on 16/8/17.
//
//

#import "FinishedOrder.h"
#import "FinishedOrderCell.h"
#import "FinishedOrderHeader.h"
#import "Pager.h"
#import "MFinishedTask.h"
#import "FinishedTaskDetailVC.h"
#import "CGXPickerView.h"
#import "SelectSegmentView.h"

#define Seg_Height 45


@interface FinishedOrder ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property(nonatomic,strong) UIView* topView;
@property(nonatomic,strong) UILabel* labelDate;
@property(nonatomic,strong) UILabel* labelCount;

@property(nonatomic,strong) UICollectionView* collectionView;
@property(nonatomic,strong) NSString* cellIdentifier;
@property(nonatomic,strong) NSString* headerIdentifier;
@property(nonatomic,strong) NSMutableArray* arrayData;
@property(nonatomic,strong) Pager* page;
@property(nonatomic,strong) NSString* timeStr;
@property (nonatomic,strong) SelectSegmentView *segView;
@property (nonatomic,assign) NSInteger seletedIndex;

@end

@implementation FinishedOrder

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"已完成的任务";
    self.cellIdentifier =  @"FinishedOrderCell";
    self.headerIdentifier =  @"FinishedOrderHeader";
    self.timeStr = @"";
    self.seletedIndex = 1;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"icon_right_calendar"] style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonDidClick)];

    
    [self layoutUI];
    [self refreshDataSource];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


-(void)rightButtonDidClick{
    
    [CGXPickerView showDatePickerWithTitle:@"请选择日期" DateType:UIDatePickerModeDate DefaultSelValue:nil MinDateStr:nil MaxDateStr:nil IsAutoSelect:NO Manager:nil ResultBlock:^(NSString *selectValue) {
        
      
        NSLog(@"===%@",selectValue);
        
        self.timeStr = selectValue;
        
        [self refreshDataSource];
        
    }];
    
}


#pragma mark =====================================================  user interface layout
-(void)layoutUI{
    
    
    _segView = [[SelectSegmentView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, Seg_Height) titles:@[@"已送达", @"已取消"] clickBlick:^void(NSInteger index) {
        
        self.seletedIndex = index;
        
        [self refreshDataSource];

    }];
    
    _segView.defaultIndex = self.seletedIndex;
    _segView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    _segView.titleNomalColor = [UIColor darkGrayColor];
    _segView.titleSelectColor = kMyColor(248, 159, 39);
    _segView.lineUnSelectColor = [UIColor whiteColor];
    _segView.titleFont = kFontNameSize(16);
    [self.view addSubview:_segView];
    [self.segView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view);
        make.height.mas_equalTo(Seg_Height);
        make.left.right.equalTo(self.view);
    }];
    
    
    [self.view addSubview:self.topView];
    [self.topView addSubview:self.labelDate];
    [self.topView addSubview:self.labelCount];
    
    [self.view addSubview:self.collectionView];
    
    [self layoutConstraints];

}

-(void)layoutConstraints{
    
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.segView.mas_bottom);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(35);
    }];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.topView.mas_bottom);
        make.bottom.left.right.equalTo(self.view);
    }];
    
    
  
    [self.labelDate mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(self.topView);
        make.left.equalTo(self.topView).offset(10);
    }];
    
    [self.labelCount mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(self.topView);
        make.right.equalTo(self.topView).offset(-10);
    }];
    
}

#pragma mark =====================================================  DataSource
-(void)queryData{
    AFHTTPSessionManager *mgr=[AFHTTPSessionManager manager];
    NSDictionary* arg = @{
                          @"ince":@"get_overorder_list",
                          @"emp_id":self.Identity.userInfo.userID,
                          @"status":@"1",
                          @"type":@(self.seletedIndex),
                          @"time":self.timeStr,
                          @"page":[WMHelper integerConvertToString:self.page.pageIndex]
                          
                          };
    [mgr POST:kHost parameters:arg progress:nil success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject) {
        [WMHelper outPutJsonString:responseObject];
        NSInteger flag = [[responseObject objectForKey:@"status"]integerValue];
        if(self.page.pageIndex == 1){
            [self.arrayData removeAllObjects];
        }
        NSInteger totalCount = 0;
        NSInteger currentCount = 0;
        if(flag == 1){
            totalCount = [[responseObject objectForKey: @"total"] integerValue];
            NSArray* array = [responseObject objectForKey:@"list"];
            if(![WMHelper isNULLOrnil:array]){
                currentCount = array.count;
                self.page.recordCount = [[responseObject objectForKey:@"total"] integerValue];
                self.page.pageSize = [[responseObject objectForKey:@"number"]integerValue];
                NSInteger empty = self.page.recordCount % self.page.pageSize;
                if(empty == 0){
                    self.page.pageCount = self.page.recordCount/self.page.pageSize;
                }else{
                    self.page.pageCount = self.page.recordCount/self.page.pageSize+1;
                }
                
                NSMutableArray *tempArr = [MOrder mj_objectArrayWithKeyValuesArray:array];
                [ self.arrayData addObjectsFromArray:tempArr];
                

            }
            
            self.labelDate.text =responseObject[@"daytime"];
            self.labelCount.text =[NSString stringWithFormat:@"完成%ld单", [responseObject[@"total"] integerValue]];
            
            
            NSInteger totalno = [responseObject[@"totalno"] integerValue];
            NSInteger totalyes = [responseObject[@"totalyes"] integerValue];

            
            _segView.titleArray = @[[NSString stringWithFormat:@"已送达(%ld)",totalyes],[NSString stringWithFormat:@"已取消(%ld)",totalno]];
            

            
        }else{
            [self alertHUD:[responseObject objectForKey:@"fail"]];
        }
        [self.collectionView reloadData];
//        if(self.page.pageCount<=self.page.pageIndex){
//            [self.collectionView.mj_footer endRefreshingWithNoMoreData];
//        }else{
//            [self.collectionView.mj_footer endRefreshing];
//        }
        if(self.page.pageIndex==1){
            [self.collectionView.mj_header endRefreshing];
        }else{
            
            if (currentCount == 0) {
                [self.collectionView.mj_footer endRefreshingWithNoMoreData];

            }else{
            [self.collectionView.mj_footer endRefreshing];

            }
        }
        
        
        
    } failure:^(NSURLSessionDataTask *_Nonnull operation, NSError * _Nonnull error) {
        [self alertHUD:@"网络异常"];
        [self.collectionView.mj_header endRefreshing];
    }];
}

-(void)refreshDataSource{
    __weak typeof(self) weakSelf = self;
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.page.pageIndex = 1;
        weakSelf.page.recordCount = 0;
        weakSelf.page.groupSection = 0;
        [weakSelf queryData];
    }];
    self.collectionView.mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
        weakSelf.page.pageIndex ++;
        [weakSelf queryData];
    }];    
    [self.collectionView.mj_header beginRefreshing];
}


#pragma mark =====================================================  UICollectionView 协议实现
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
//    return self.arrayData.count;
    
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
//    MFinishedTask* empty = self.arrayData[section];
//    return empty.arrayOrder.count;
    
    return self.arrayData.count;

    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    FinishedOrderCell *cell = (FinishedOrderCell*)[collectionView dequeueReusableCellWithReuseIdentifier:self.cellIdentifier forIndexPath:indexPath];
//    MFinishedTask* empty = self.arrayData[indexPath.row];
//    cell.entity = empty.arrayOrder[indexPath.row];
    
    cell.entity = self.arrayData[indexPath.row];

//    cell.arrayOrder = empty.arrayOrder;
    cell.tag = indexPath.row;
    UITapGestureRecognizer *tapgr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gestureTouch:)];
    [cell addGestureRecognizer:tapgr];
    return cell;
}


-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if([kind isEqualToString:UICollectionElementKindSectionHeader]){
//        UICollectionReusableView  *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:self.headerIdentifier forIndexPath:indexPath];
//        FinishedOrderHeader* emptyHeader = (FinishedOrderHeader*)reusableView;
//        emptyHeader.entity = self.arrayData[indexPath.section];
//        return reusableView;
    }
    return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    
//    MFinishedTask* empty = self.arrayData[indexPath.section];
//    __block CGFloat height = 0.f;
//    height+=170.f;
////    MOrder* item = empty.arrayOrder[indexPath.row];
//
//    MOrder *item = self.arrayData[indexPath.row];
//    [item.arrayStore enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//        height+=35.f;
//    }];
    
    
    return CGSizeMake(SCREEN_WIDTH, 210);
}


-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(10.f, 0.f, 0.f, 0.f);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
//    return CGSizeMake(SCREEN_WIDTH, 35);
    
    return CGSizeMake(0, 0);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    
    return 10.f; /// 行与行之间的间隔距离
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 10.f; //相邻两个 item 间距
}

#pragma mark =====================================================  SEL
-(void)gestureTouch:(UIGestureRecognizer*)sender{
    FinishedOrderCell* cell = (FinishedOrderCell*)sender.view;
    FinishedTaskDetailVC* controller = [[FinishedTaskDetailVC alloc]init];
    controller.main_id = cell.entity.main_id;
    [self.navigationController pushViewController:controller animated:YES];
}

#pragma mark =====================================================  private method
-(void)loadDataTitel:(NSString*)title{
    if(title){
//        title = [NSString stringWithFormat:@"%@单",title];
//        NSString* str = [NSString stringWithFormat:@"累计单量 : %@",title];
//        NSMutableAttributedString* attributeStr = [[NSMutableAttributedString alloc]initWithString:str];
//        [attributeStr addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:24.f],NSForegroundColorAttributeName:[UIColor colorWithRed:248/255.f green:159/255.f blue:39/255.f alpha:1.0]} range:[str rangeOfString:title]];
//        self.topView.attributedText = attributeStr;
    }else{
        
    }
}

#pragma mark =====================================================  property package
-(UIView *)topView{
    if(!_topView){
        _topView = [[UIView alloc]init];
        _topView.backgroundColor = [UIColor colorWithRed:254/255.f green:228/255.f blue:181/255.f alpha:1.0];
    }
    return _topView;
}
-(UILabel *)labelDate{
    if(!_labelDate){
        _labelDate = [[UILabel alloc]init];
        _labelDate.textAlignment = NSTextAlignmentLeft;
        _labelDate.translatesAutoresizingMaskIntoConstraints = NO;
    }
    return _labelDate;
}

-(UILabel *)labelCount{
    if(!_labelCount){
        _labelCount = [[UILabel alloc]init];
        _labelCount.textAlignment = NSTextAlignmentRight;
        _labelCount.textColor = [UIColor colorWithRed:83/255.f green:83/255.f blue:83/255.f alpha:1.0];
        _labelCount.translatesAutoresizingMaskIntoConstraints = NO;
    }
    return _labelCount;
}


-(UICollectionView *)collectionView{
    if(!_collectionView){
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:[[UICollectionViewFlowLayout alloc]init]];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [self.collectionView registerClass:[FinishedOrderCell class] forCellWithReuseIdentifier:self.cellIdentifier];
        [self.collectionView registerClass:[FinishedOrderHeader class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:self.headerIdentifier];
        _collectionView.translatesAutoresizingMaskIntoConstraints = NO;
        _collectionView.backgroundColor = [UIColor groupTableViewBackgroundColor];
        
    }
    return _collectionView;
}

-(NSMutableArray *)arrayData{
    if(!_arrayData){
        _arrayData = [[NSMutableArray alloc]init];
    }
    return _arrayData;
}

-(Pager *)page{
    if(!_page){
        _page = [[Pager alloc]init];
        _page.pageIndex = 1;
    }
    return _page;
}

@end
